/*
* This file is a part of the open-eBackup project.
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* Copyright (c) [2024] Huawei Technologies Co.,Ltd.
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*/
#include "InquireHandler.h"

#include <map>
#include <thread>
#include <fstream>
#include <iostream>
#include <functional>
#include "BackintConst.h"
#include "common/File.h"

using namespace backint;

namespace {
    const std::string INQUIRE_SUCCESS = "#BACKUP";
    const std::string INQUIRE_ERROR = "#ERROR";
    const std::string INQUIRE_NOTFOUND = "#NOTFOUND";
}

uint32_t InquireHandler::ExecInquire(const StuParam &inParam, const PlugParams &plugParam)
{
    LOGGUARD("");
    GetInquireParam(inParam, plugParam);
    StuFileInfo stFileInfo;
    if (ReadPipeInfo(inParam.m_inputFile, stFileInfo) != SUCCESS) {
        ERRLOG("Failed to get backup info, jobId=%s, subJobId=%s.", m_jobId.c_str(), m_subJobId.c_str());
        return FAILED;
    }
    std::vector<std::string> outFileTitle = {stFileInfo.m_inputFileTitle};
    if (WriteOutFile(outFileTitle, m_outputFile) != SUCCESS) {
        ERRLOG("Failed to write output file.");
        return FAILED;
    }
    for (const auto &it : stFileInfo.m_eBIDData) {
        if (CreateDirIfNotExist(it.m_filePath) != SUCCESS) {
            return FAILED;
        }
        std::string filePath = m_dataPath + "/" + GetFileName(it.m_filePath);
        if (!Module::CFile::FileExist(filePath)) {
            m_outputResult = {INQUIRE_NOTFOUND, it.m_filePath};
        } else {
            m_outputResult = {INQUIRE_SUCCESS, it.m_backupID, it.m_filePath};
        }
        if (WriteOutFile(m_outputResult, m_outputFile) != SUCCESS) {
            ERRLOG("Failed to write output file.");
            return FAILED;
        }
    }
    return SUCCESS;
}

void InquireHandler::GetInquireParam(const StuParam &inParam, const PlugParams &plugParam)
{
    LOGGUARD("");
    m_pid = plugParam.m_pid;
    m_dbName = plugParam.m_dbName;
    m_jobId = plugParam.m_jobId;
    m_subJobId = plugParam.m_subJobId;
    m_cachePath = plugParam.m_cachePath;
    m_dataPath = plugParam.m_dataPath;
    m_outputFile = inParam.m_outFile;
    m_backupID = inParam.m_dtBackupId;
}

uint32_t InquireHandler::CreateDirIfNotExist(const std::string &inFile)
{
    std::string parentPath = inFile.substr(0, inFile.find_last_of('/'));
    if (!Module::CFile::DirExist(parentPath.c_str())) {
        if (Module::CFile::CreateDir(parentPath.c_str()) != SUCCESS) {
            INFOLOG("Create dir failed, dir: %s.", parentPath.c_str());
            return FAILED;
        }
    }
    return SUCCESS;
}